package org.grow.took.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.grow.took.dao.UserInfoDao;
import org.grow.took.entity.UserInfo;
import org.grow.took.entity.UserInfoDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.CharacterEncodingFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @Author: xwg
 * @CreateDate: 2021/9/30
 */
//登录第四步
@Service
public class AuthHandler implements AuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private UserInfoDao userInfoDao;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
//        个性称呼       Security框架    JDK
//        UserInfo  ==  UserDetails  == Principle  === 80%Authentication

        System.out.println("用户登录成功： "+authentication.getPrincipal());
        httpServletResponse.setStatus(200);
        UserInfo principal = (UserInfo) authentication.getPrincipal();
        UserInfoDto userInfoDto = new UserInfoDto();
        BeanUtils.copyProperties(principal,userInfoDto);
//        userInfoDto.setUsername(principal.getUsername());
//        httpServletResponse.setCharacterEncoding("utf8");

        httpServletResponse.getWriter().println(
                objectMapper.writeValueAsString(userInfoDto));
//      给前端的信息已经完成。
//        更新后端登录时间
        principal.setLastLoginTime(LocalDateTime.now());
        userInfoDao.updateById(principal);



    }
}
